package com.zhinan.config;

import com.google.code.kaptcha.text.impl.DefaultTextCreator;

import java.security.SecureRandom;
import java.util.Random;

/**
 * @Description: Kaptcha生成数学计算验证码的自定义文本生成器
 * @Author: ZhiNan
 * @Date: 2023-04-21 11:32
 * @Version: 1.0
 */
public class KaptchaTextCreator extends DefaultTextCreator {


    private static final String[] NUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(",");


    @Override
    public String getText() {
        Integer result = 0;
        Random random = new SecureRandom();
        int x = random.nextInt(10);
        int y = random.nextInt(10);
        StringBuilder suChinese = new StringBuilder();
        int operatorFlag = (int) Math.round(Math.random() * 2);  //生成随机数表示+ — * /

        if (operatorFlag == 0) {   //乘法
            result = x * y;
            suChinese.append(NUMBERS[x]);
            suChinese.append("*");
            suChinese.append(NUMBERS[y]);
        } else if (operatorFlag == 1) {   //除法
            if (!(x == 0) && y % x == 0) {
                result = y / x;
                suChinese.append(NUMBERS[y]);
                suChinese.append("/");
                suChinese.append(NUMBERS[x]);
            } else {
                result = x + y;
                suChinese.append(NUMBERS[x]);
                suChinese.append("+");
                suChinese.append(NUMBERS[y]);
            }
        } else if (operatorFlag == 2) {   //减法
            if (x >= y) {
                result = x - y;
                suChinese.append(NUMBERS[x]);
                suChinese.append("-");
                suChinese.append(NUMBERS[y]);
            } else {
                result = y - x;
                suChinese.append(NUMBERS[y]);
                suChinese.append("-");
                suChinese.append(NUMBERS[x]);
            }
        } else {   //加法
            result = x + y;
            suChinese.append(NUMBERS[x]);
            suChinese.append("+");
            suChinese.append(NUMBERS[y]);
        }
        //返回的运算表达式和结果  用@符号分割
        suChinese.append("=?@" + result);
        return suChinese.toString();
    }
}
